package com.buba.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.buba.pojo.user.User;
import com.buba.user.mapper.UserMapper;
import com.buba.user.service.MsmService;
import com.buba.user.service.UserService;
import com.buba.utils.*;
import com.buba.pojo.user.User;
import lombok.extern.slf4j.Slf4j;
import com.buba.user.utils.MybatisPageHelper;
import com.buba.user.utils.PageRequest;
import com.buba.user.utils.PageResult;
import com.buba.user.vo.AppointmentVo;
import com.buba.user.vo.MedicalAppointmentVo;
import com.buba.user.vo.NucleicAcidVo;
import com.buba.utils.R;
import io.swagger.annotations.ApiOperation;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.buba.pojo.other.DivisionType;
import com.buba.pojo.other.Drugs;
import org.springframework.web.bind.annotation.*;
import com.buba.pojo.other.SetMeal;
import com.buba.pojo.record.*;
import com.buba.pojo.user.Campus;
import com.buba.pojo.user.Doctor;
import com.buba.pojo.user.ThePatient;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Date;
/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-06-09
 */
@Slf4j
@RestController
@RequestMapping("/user/user")
public class UserController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserService userService;



    /**
     * @Author 梁玉杰
     * @Description //测试的 所有用户列表
     * http://localhost:8050/user/user/user/findAll
     * http://localhost:9000/user/user/user/findAll
     * @param
     * @Return com.buba.utils.R
     * @throws
     * @Date 2022/6/9 13:42
     **/
    @ApiOperation(value = "所有用户列表")
    @GetMapping("/findAll")
    public R findAllTeacher(){
        List<User> list = userService.list(null);
        return R.ok().data("userList",list);
    }

    //修改用户头像
    @PostMapping("/uploadFile/{id}")
    public R uploadFile(MultipartFile file , @PathVariable Integer id){
        String url = userService.uploadFile(file , id);
        return R.ok().data("url" , url);
    }
    //忘记密码
    @PostMapping("/resetPwd")
    public R resetPwd(@RequestBody User user) {
        int i = userService.resetPwd(user);
        if (i > 0) {
            return R.ok().data("message", "修改成功");
        } else {
            return R.error().data("message", "修改失败");
        }
    }

    //注册
    @PostMapping("/regirect")
    public R regirect(@RequestBody User user) {

        user.setPassword(MD5.convertMD5(user.getPassword()));

        user.setUserRole("用户");

        Calendar calendar = Calendar.getInstance();//获取时间
        user.setCreationTime(calendar.getTime());
        user.setModificationTime(calendar.getTime());

        log.info("user:::" + user);

        boolean save = userService.save(user);
        if (save) {
            return R.ok().data("message", "注册成功");
        } else {
            return R.error().data("message", "注册失败");
        }
    }

    //登陆
    @PostMapping("/login")
    public R login(@RequestBody User user) {

        log.info("user::" + user);
        user.setPassword(MD5.convertMD5(user.getPassword()));
        User user1 = userService.login(user);

        Map<String, Object> map = new HashMap<>();
        map.put("token", user1.getToken());
        map.put("user", user1);

        log.info("token::" + user1.getToken());


        return R.ok().data(map);
    }

    //获取验证码
    @GetMapping("/getCode/{userPhone}")
    public R getCode(@PathVariable String userPhone) {
        log.info("userPhone:::::::" + userPhone);

        Object code = redisUtil.get(userPhone);
        System.out.println("code:::::::" + code);

        return R.ok().data("code", code);

    }

    //发送验证码
    @GetMapping("/send/{userPhone}")
    public R sendMsm(@PathVariable String userPhone) {
        log.info("phone:::::::" + userPhone);

        //判断手机号是否重复
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone" , userPhone);
        User one = userService.getOne(wrapper);
        if (one != null){
            return R.error().data("message" , "手机号已存在");
        }

        //先从redis里取验证码
        String s = redisTemplate.opsForValue().get(userPhone);
        if (!StringUtils.isEmpty(s)) {
            return R.ok().data("code", s);
        }

        String code = RandomUtil.getFourBitRandom();

        Map<String, Object> map = new HashMap<>();
        map.put("code", code);

        boolean isSend = msmService.sendMsm(map, userPhone);
        if (isSend) {
            redisUtil.set(userPhone, code, 60);//将验证码存入redis并设置一分钟时长
            return R.ok().data("code", code);
        } else {
            return R.error().message("短信发送失败");
        }

    }



    /*
     * @Author: 张庆威
     * @Description: (将就诊人加入到redis中 进行排队)
     * @Date: 16:20 2022/6/16
     * @Param: [userPhone]
     * @return: com.buba.utils.R
     **/
    @GetMapping("/setRedis/{patientId}")
    public R setRedis(@PathVariable("patientId") String patientId){
        log.info("patientId:::::::"+patientId);


        //以就诊人id为键值存储
        boolean b = redisUtil.lSet("queue", patientId);
        log.info("添加结果=="+b);

        List<Object> queue= redisUtil.lGet("queue", 0, -1);
        log.info("队列结果=="+queue);
        return R.ok();

    }

    //登录
    @PostMapping("/login2")
    public R login2(@RequestBody User user){
        System.out.println("进入");
        System.out.println(user.getUserName());
        User user1=userService.login(user.getUserName());

        if(user1!=null){
            if (user.getPassword().equals(user1.getPassword())){
                UUID s=UUID.randomUUID();
                String token=s.toString();
                String loginUser=user.getUserName();
                Date date=new Date();
                userService.insertToken(token,loginUser,date);
                HashMap<Object,Object> map=new HashMap<>();
                map.put("token",s);
                return R.ok().data("map",map);
            }else {
                return R.error().data("密码不正确",0);
            }
        }else {
            return R.error().data("用户名不存在",0);
        }
    }


    //挂号全查
    @PostMapping("/getAllappointment")
    public R getAllappointment(@RequestBody PageRequest pageRequest){
//        log.info("doctorName==="+pageRequest.getDoctorName());
//        log.info("name==="+pageRequest.getName());
//        log.info("createTime==="+pageRequest.getCreateTime());
//        log.info("createTime==="+pageRequest.getDivisionName());
        MybatisPageHelper.startPage(pageRequest);
        List<AppointmentVo> list=userService.getAllappointment(pageRequest.getDoctorName(),
                pageRequest.getName(),pageRequest.getCreateTime(),
                pageRequest.getCreateTime1(),pageRequest.getDivisionName());
        PageResult pageResult=MybatisPageHelper.getPageResult(list);
        return R.ok().data("pageResult",pageResult);

    }

    //单查
    @GetMapping("/getByIdappointment/{id}")
    public R getByIdappointment(@PathVariable("id") Integer id){
        AppointmentVo appointment=userService.getByIdappointment(id);

        //医生单查
        Doctor d = userService.getByIdDoctor(appointment.getDoctorId());
//        log.info("d==="+d);
        //就诊人单查
        ThePatient tp=userService.getByIdThePatient(appointment.getPatientId());
//        log.info("tp==="+tp);
        //候诊记录单查
        WaitingRecord wr=userService.getByIdWaitingRecord(appointment.getHouzhenId());
//        log.info("wr==="+wr);
        //科室
        DivisionType dt=userService.getByIdDivisionType(appointment.getDepartmentId());
//        log.info("dt==="+dt);
        //院区单查
        Campus c=userService.getByidCampus(appointment.getCampusId());

        return R.ok().data("id",appointment).data("d",d).data("tp",tp).data("dt",dt).data("c",c).data("wr",wr);
    }

    //核酸检查
    @PostMapping("/getAllnucleicAcid")
    public R getAllnucleicAcid(@RequestBody PageRequest pageRequest){
        log.info("createTime==="+pageRequest.getCreateTime());
        log.info("createTime1==="+pageRequest.getCreateTime1());

        MybatisPageHelper.startPage(pageRequest);
        List<NucleicAcidVo> list=userService.getAllnucleicAcid(pageRequest.getCreateTime(),pageRequest.getCreateTime1());
        PageResult pageResult=MybatisPageHelper.getPageResult(list);
        return R.ok().data("pageResult",pageResult);
    }

    //核酸单查
    @GetMapping("/getByIdnucleicacid/{id}")
    public R getByIdnucleicacid(@PathVariable("id") Integer id){
        NucleicAcidVo nucleicacid=userService.getByIdnucleicacid(id);
        //医生单查
        Doctor d = userService.getByIdDoctor1(nucleicacid.getDoctorId());
        //就诊人单查
        ThePatient tp=userService.getByIdThePatient1(nucleicacid.getPatientId());
        log.info("tp==="+tp);
        //候诊记录单查
        WaitingRecord wr=userService.getByIdWaitingRecord1(nucleicacid.getHouzhenId());
        log.info("wr==="+wr);
        //科室
        DivisionType dt=userService.getByIdDivisionType1(nucleicacid.getDepartmentId());
        log.info("dt==="+dt);
        //院区单查
        Campus c=userService.getByidCampus1(nucleicacid.getCampusId());
        log.info("c==="+c);
        return R.ok().data("nucleicacid",nucleicacid).data("hsThePatient",tp).data("hsDivisionType",dt)
                .data("hsCampus",c).data("hsWaitingRecord",wr).data("hsdocrot",d);
    }

    //体检全查
    @PostMapping("/getAllmedicalAppointment")
    public R getAllmedicalAppointment(@RequestBody PageRequest pageRequest){

        log.info("pageRequest"+pageRequest.getPageNum());
        MybatisPageHelper.startPage(pageRequest);
        List<MedicalAppointmentVo> list=userService.getAllmedicalAppointment(pageRequest.getCreateTime(),pageRequest.getCreateTime1());
         PageResult pageResult=MybatisPageHelper.getPageResult(list);
        return R.ok().data("pageResult",pageResult);
    }
    //体检单查
    @GetMapping("/getByIdmedicalAppointment/{id}")
    public R getByIdmedicalAppointment(@PathVariable("id") Integer id){
        MedicalAppointmentVo medicalAppointment=userService.getByIdmedicalAppointment(id);
        //就诊人单查
        ThePatient thePatient=userService.getByIdThePatient2(medicalAppointment.getPatientId());
       //套餐类型单查
        SetMeal setMeal=userService.getBiIdsetMeal(medicalAppointment.getPackageId());
        //体检报告单查
//        PhysicalReport physicalReport=userService.getBiIdphysicalReport(medicalAppointment.get)
        //院区单查
        Campus campus=userService.getByidCampus2(medicalAppointment.getCampusId());
        //科室
        DivisionType divisionType=userService.getByIdDivisionType2(medicalAppointment.getDepartmentId());
        //体检报告单查
        PhysicalReport physicalReport=userService.getByIdPhysicalReport(medicalAppointment.getPatientId());


//        Convention convention=userService.getAllconvention(medicalAppointment.getPatientId());
        return R.ok().data("medicalAppointment",medicalAppointment).data("thePatient",thePatient)
                .data("setMeal",setMeal).data("campus",campus).data("divisionType",divisionType)
                .data("physicalReport",physicalReport);
    }

    //常规检查
    @GetMapping("/getAllconvention/{patientId}")
    public R getAllconvention(@PathVariable("patientId") Integer patientId){
        Convention convention=userService.getAllconvention(patientId);
        return R.ok().data("convention",convention);
    }

    //血常规检查
    @GetMapping("/getAllbloodRoutineExaminatio/{patientId}")
    public R getAllbloodRoutineExaminatio(@PathVariable("patientId") Integer patientId){
        BloodRoutineExaminatio bloodRoutineExaminatio=userService.getAllbloodRoutineExaminatio(patientId);
        return R.ok().data("bloodRoutineExaminatio",bloodRoutineExaminatio);
    }

    //门诊消费记录
    //体检全查
    @PostMapping("/getAllrecord")
    public R getAllrecord(@RequestBody PageRequest pageRequest){

//        log.info("pageRequest"+pageRequest.getPageNum());
        MybatisPageHelper.startPage(pageRequest);
        List<MedicalAppointmentVo> list=userService.getAllrecord();
        PageResult pageResult=MybatisPageHelper.getPageResult(list);
        return R.ok().data("pageResult",pageResult);
    }

    //药品表全查
    @GetMapping("/getAlldrugs")
    public R getAlldrugs(){
        List<Drugs> list=userService.getAlldrugs();
        return R.ok().data("list",list);
    }

    //药品表单查
    @GetMapping("/getByIddrugs/{drugId}")
    public R getByIddrugs(@PathVariable("drugId") Integer id){
        Drugs drugs=userService.getByIddrugs(id);
        return R.ok().data("drugs",drugs);
    }






//    //添加病历
//    @PostMapping("/medicalRecords")
//    public R medicalRecords(MedicalRecords medicalRecords, ThePatient thePatient, DrugRecord drugRecord){
//        //添加病历表格
////        int m=userService.addmedicalRecords(medicalRecords);
//
////        //修改就诊人表
//        int u=userService.uodatethePatient(thePatient);
//
////        DrugRecord drugRecord1=new DrugRecord();
////        drugRecord1.setSerialNumber(RandomUtil.getSixBitRandom());
//        //药品记录表
////        int d=userService.adddrugRecord(drugRecord1);
//
////        if(u>0&&d>0){
////            return R.ok().data("ok","添加成功");
////        }else {
////            return R.error().data("error","添加失败");
////        }
////        return R.ok().data("ok",1);
//    }



//    //导入
//    @GetMapping("/export")
//    public void export(HttpServletResponse response) throws Exception {
//        // 从数据库查询出所有的数据
//        List<AppointmentVo> list = userService.getAllappointment(null);
//        // 通过工具类创建writer 写出到磁盘路径
////        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
//        // 在内存操作，写出到浏览器
//        ExcelWriter writer = ExcelUtil.getWriter(true);
//        //自定义标题别名
//        writer.addHeaderAlias("name", "患者姓名");
//        writer.addHeaderAlias("hospitalNumber", "就诊卡号");
//        writer.addHeaderAlias("number", "身份证号");
//        writer.addHeaderAlias("phone", "手机号码");
//        writer.addHeaderAlias("divisionName", "挂号科室");
//        writer.addHeaderAlias("jobTitle", "挂号类型");
//        writer.addHeaderAlias("registration", "挂号费");
//        writer.addHeaderAlias("state", "挂号状态");
//        writer.addHeaderAlias("createTime", "就诊日期");
//        writer.addHeaderAlias("houzhenTime", "候诊时间");
//        writer.addHeaderAlias("createTime", "预约时间");
//
//        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
//        writer.write(list, true);
//
//        // 设置浏览器响应的格式
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//        String fileName = URLEncoder.encode("用户信息", "UTF-8");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
//
//        ServletOutputStream out = response.getOutputStream();
//        writer.flush(out, true);
//        out.close();
//        writer.close();
//    }


//    @PostMapping("/import")
//    public Boolean imp(MultipartFile file) throws Exception {
//        InputStream inputStream = file.getInputStream();
//        ExcelReader reader = ExcelUtil.getReader(inputStream);
//        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
////        List<User> list = reader.readAll(User.class);
//
//        // 方式2：忽略表头的中文，直接读取表的内容
//        List<List<Object>> list = reader.read(1);
//        List<AppointmentVo> users = CollUtil.newArrayList();
//        for (List<Object> row : list) {
//            AppointmentVo user = new AppointmentVo();
//
//            user.setUsername(row.get(0).toString());
//            user.setPassword(row.get(1).toString());
//            user.setNickname(row.get(2).toString());
//            user.setEmail(row.get(3).toString());
//            user.setPhone(row.get(4).toString());
//            user.setAddress(row.get(5).toString());
//            user.setAvatarUrl(row.get(6).toString());
//            users.add(user);
//        }
//
//        userService.saveBatch(users);
//        return true;
//    }


}

